<template>
  <div>
    <div v-show="!modal.show">
      <a-form layout="inline" class="nmv-search-form-auto" :labelCol="{ style: 'width: 100px' }"
        style="padding:20px 20px 0;background-color:white;">
        <a-form-item label="是否自有车辆">
          <a-select placeholder="请选择" allowClear @change="searchQuerys" v-model="grid.queryParams.qqVehicle" class="nmv-w-200">
            <a-select-option value="1">是</a-select-option>
            <a-select-option value="2">否</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="车牌号" >
          <a-input class="nmv-w-200" v-model="grid.queryParams.licensePlate" placeholder="请输入车牌号"></a-input>
        </a-form-item>
        <a-form-item label="预警时间">
          <a-range-picker style="width:266px" v-model="time" @change="rangeTimeOk" :show-time="{
            hideDisabledOptions: true,
          }" format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']" @ok="rangeTimeOk" />
        </a-form-item>
        <a-form-item label="所属企业" >
          <a-select class="nmv-w-200" allowClear show-search :filter-option="filterOption" v-model="grid.queryParams.companyId" placeholder="全部企业"
             @change="brandOptionsChange">
            <a-select-option v-for="(item, i) in companiesAllList" :key="i" :value="item.id">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属门店">
          <a-select placeholder="全部门店" allowClear show-search :filter-option="filterOption" @change="searchQuerys"
            class=" nmv-w-200" v-model="grid.queryParams.storeId">
            <a-select-option v-for="item in storeList" :key="item.id" :value="+item.id">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="处理状态">
          <a-select placeholder="请选择状态" allowClear @change="searchQuerys" v-model="grid.queryParams.status"
            class="nmv-w-200">
            <a-select-option value="1">已处理</a-select-option>
            <a-select-option value="0">未处理</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="骑手姓名" >
          <a-input class="nmv-w-200" v-model="grid.queryParams.riderName" placeholder="请输入骑手姓名"></a-input>
        </a-form-item>
        <a-form-item label="骑手电话" >
          <a-input class="nmv-w-200" v-model="grid.queryParams.riderPhone" placeholder="请输入骑手电话"></a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="searchQuerys">查询</a-button>
          <a-button style="margin-left:12px" @click="queryReset">重置</a-button>
        </a-form-item>
        <a-form-item style="float:right;margin:0">
          <div style="display:flex;justify-content: end;">
            <permissions type="customerService/customerServiceManager/fence/warning/export">
              <a-button class="float-r xian_btn" style="margin-right: 20px;"  @click="onExport">导出</a-button>
            </permissions>
            <permissions type="customerService/customerServiceManager/fence/warning/batchProcess">
              <a-button class="float-r" style="margin-right: 12px;"  type="primary" ghost @click="onDistribution">批量处理</a-button>
            </permissions>
          </div>
        </a-form-item>
      </a-form>

      <a-card :bordered="false" :bodyStyle="{ padding: '0px 20px 20px' }">
        <a-table :locale="locale" :pagination="false" :scroll="{x:1300}" :loading="grid.load" :columns="grid.columns" :row-selection="rowSelection" rowKey="id" :data-source="grid.data">
          <span slot="riderName" slot-scope="text, record">
            <div class="flex_start">
              <span style="color: #333333;font-size:14px">{{record.riderName||'-'}}</span>
            </div>
            <div class="flex_start" >
              <span style="color: #999999;font-size:12px">{{record.riderPhone||'-'}}</span>
            </div>
          </span>
          <span slot="alarmTime" slot-scope="text, record">
            <div class="flex_start">
              <span style="color: #333333;font-size:14px">{{record.alarmLocation||'-'}}</span>
            </div>
            <div class="flex_start" >
              <span style="color: #999999;font-size:12px">{{record.alarmTime||'-'}}</span>
            </div>
          </span>
          <span slot="companyId" slot-scope="text, record">
            <div class="flex_start">
              <span style="color: #333333;font-size:14px">
                <span v-for="(item,index) in companiesAllList" :key="index">
                  <span v-if="record.companyId==item.id">{{item.name}}</span>
                </span>
              </span>
            </div>
            <div class="flex_start" >
              <span style="color: #999999;font-size:12px">
                <span v-for="(item,index) in storeList" :key="index">
                  <span v-if="record.storeId==item.id">{{item.name}}</span>
                </span>
              </span>
            </div>
          </span>
          <span slot="status" slot-scope="text">
            <div class="flex_start" v-show="text == 0">
              <div class="yuan red"></div>
              <div>未处理</div>
            </div>
            <div class="flex_start" v-show="text == 1">
              <div class="yuan green"></div>
              <div>已处理</div>
            </div>
          </span>
          <span slot="licensePlate" slot-scope="text">
              <span>
                <!-- <a :href="`/#/vehicle/vehicleManager/vehicleList?vehiclePlate=${record.licensePlate}&id=${record.vehicleId}`" target="_blank"> -->
                  {{ text }}
                <!-- </a> -->
              </span>
          </span>
          <span slot="action" slot-scope="text, record">
            <permissions type="customerService/customerServiceManager/fence/warning/process">
              <a-popconfirm
                title="是否将该车辆预警设为已处理状态"
                placement="top"
                ok-text="确定"
                cancel-text="取消"
                @confirm="dispose(record)"
                @cancel="cancel"
              >
              <a v-if="record.status==0" href="#" class="button_right">处理</a>
            </a-popconfirm>
            </permissions>
          </span>
        </a-table>
        <div v-show="grid.total !== 0" style="text-align:right;">
          <a-pagination show-size-changer :current="grid.queryParams.pageNum" :pageSize="grid.queryParams.pageSize"
            @change="onChange" @showSizeChange="onShowSizeChange" style="margin-top:20px;" size="small"
            :total="grid.total" :show-total="total => `共${grid.total}条 `" />
        </div>
      </a-card>

    </div>
    <div v-show="modal.show"></div>
  </div>
</template>

<script>
import { vehicleOptions } from '@/utils/options.js'
import { alarmList, flagAlarm, batchAlarm, exportAlarm } from '@/services/car'
import { stateTextStyle, cardTitleStyle } from '@/utils/style.js'
import { readAll } from '@/services/helpCenter'
import { downLoads } from '@/utils/util.js'
import permissions from '@/components/permissions'
import { companiesAllList, exportException, getAllStore } from '@/services/rider'
import Empty from '@/components/Empty/Empty'
import moment from 'moment'

export default {
  name: 'VehicleList',
  components: {
    permissions
  },
  data () {
    return {
      moment,
      locale: {
        emptyText: <Empty />
      },
      time: [],
      storeList: [],
      activeName: 1,
      cardTitleStyle,
      selectedRowKeys: [],
      title: '',
      content: '',
      titleData: '',
      modal: {
        show: false,
        data: {}
      },
      preview: {
        show: false,
        list: []
      },
      // 数据列表
      grid: {
        load: false,
        total: 0,
        queryParams: {
          pageSize: 10,
          pageNum: 1
        },
        data: [],
        columns: [

          {
            title: '车牌号',
            dataIndex: 'licensePlate',
            scopedSlots: { customRender: 'licensePlate' },
            key: 'licensePlate',
            width: 110
          },
          {
            title: '骑手姓名',
            dataIndex: 'riderName',
            key: 'riderName',
            width: 110,
            scopedSlots: { customRender: 'riderName' }
          },
          {
            title: '预警时间位置',
            dataIndex: 'alarmTime',
            key: 'alarmTime',
            width: 220,
            scopedSlots: { customRender: 'alarmTime' }
          },
          {
            title: '当前位置',
            dataIndex: 'currentLocation',
            key: 'currentLocation',
            width: 200
          },
          {
            title: '状态',
            key: 'status',
            dataIndex: 'status',
            width: 110,
            scopedSlots: { customRender: 'status' }
          },
          {
            title: '所属企业/门店',
            key: 'companyId',
            dataIndex: 'companyId',
            width: 200,
            scopedSlots: { customRender: 'companyId' }
          },
          {
            title: '操作',
            width: 90,
            key: 'action',
            fixed: 'right',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ]
      },

      stateStyle: Object.freeze(stateTextStyle),
      orgOptions: [],
      vehicleOptions,
      brandOptions: [],
      companiesAllList: [],
      readList: {},
      selectedRowKey: []
    }
  },
  computed: {
    rowSelection () {
      return {
        fixed: true,
        onChange: (selectedRowKeys, selected) => {
          this.selectedRowKeys = selectedRowKeys
          const params = this.selectedRowKey.concat(selected)
          const map = {}
          const data = []
          params.forEach(el => {
            if (!map[JSON.stringify(el)]) {
              map[JSON.stringify(el)] = true
              data.push(el)
            }
          })
          this.selectedRowKey = data.filter(ele => {
            return this.selectedRowKeys.find(prop => {
              return prop === ele.id
            })
          })
        },
        selectedRowKeys: this.selectedRowKeys,
        getCheckboxProps: record => ({
          props: {
            disabled: record.status !== 0 // Column configuration not to be checked
          }
        })
      }
    }
  },
  created () {
    this.getLists()
    this.getList()
    this.modelGet()
  },
  methods: {

    async readAllBtn () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.newFun('请至少选择一辆待完善车辆', 'error', 3)
      }
      this.readList = {}
      Object.keys(this.grid.queryParams).forEach(v => {
        if (!['pageNum', 'pageSize'].includes(v) && this.grid.queryParams[v]) {
          this.readList.ids = this.grid.data.map(v => v.id)
        }
      })
      const res = await readAll(this.readList)
      if (res.isSuccess) {
        this.searchQuerys()
      } else {
        this.$message.newFun(res.msg, 'error', 3)
      }
    },
    // 导出
    async onExport () {
      const res = await exportAlarm()
      downLoads('电子围栏预警.xlsx', res)
    },
    rangeTimeOk (value) {
      if (value.length > 0) {
        const [start, end] = value
        this.grid.queryParams.beginAlarmTime = start.format(
          'YYYY-MM-DD'
        )
        this.grid.queryParams.endAlarmTime = end.format('YYYY-MM-DD')
        this.searchQuerys()
      } else {
        this.time = []
        delete this.grid.queryParams.beginAlarmTime
        delete this.grid.queryParams.endAlarmTime
        this.searchQuerys()
      }
    },

    brandOptionsChange () {
      delete this.grid.queryParams.storeId
      // this.modelGet()
      this.searchQuerys()
    },
    // 全部门店
    async modelGet () {
      const res = await getAllStore()
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.storeList = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    // 全部企业
    async getLists () {
      const res = await companiesAllList()
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.companiesAllList = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },

    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    onChange (page, pageSize) {
      this.grid.queryParams.pageNum = page
      console.log(pageSize)
      this.searchQuery()
    },

    // 搜索
    searchQuery () {
      this.getList()
    },
    searchQuerys () {
      this.grid.queryParams.pageNum = 1
      this.grid.queryParams.pageSize = 10
      this.getList()
    },
    onShowSizeChange (current, pageSize) {
      this.grid.queryParams.pageNum = 1
      this.grid.queryParams.pageSize = pageSize
      console.log(current)
      this.searchQuery()
    },

    // 列表
    async getList () {
      this.grid.load = true
      const res = await alarmList(this.grid.queryParams)
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.grid.data = response.records
        this.grid.total = response.total
        this.grid.load = false
      } else {
        this.$message.newFun(msg, 'error', 2)
        this.grid.data = []
        this.grid.total = 0
        this.grid.load = false
      }
    },

    // 重置
    queryReset () {
      this.time = []
      // this.storeList = []
      this.grid.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    // 处理
    async dispose (data) {
      const res = await flagAlarm({ fenceAlarmId: data.id })
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.$message.newFun('操作成功', 'success', 3)
        this.getList()
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    // 取消
    cancel () {},

    // 批量处理
    async onDistribution () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.newFun('请至少选择一个车辆', 'error', 3)
      } else {
        const res = await batchAlarm({ fenceAlarmIds: this.selectedRowKeys })
        const { isSuccess, data: response, msg } = res
        if (isSuccess) {
          this.$message.newFun('批量操作成功', 'success', 3)
          this.getList()
          this.selectedRowKeys = []
        } else {
          this.$message.newFun(msg, 'error', 2)
        }
      }
    }
  }

}
</script>
